%function [DataOut] = StatBlinks(B)

clear all; close all;
[B] = BlinkDurPop(1);

VarNames = {'CL_H_win', 'CL_L_win', 'Dis_H_win', 'Dis_L_win', 'Urg_H_win', 'Urg_L_win',...
            'MW_H_win', 'MW_L_win', 'Int_H_win', 'Int_L_win'};


load('D:\Users\zhaga\Documents\MATLAB\AFOSR_Data\Subjects\SubFolderList.mat')


for i = 1:length(SubFolderList(:,3))
    SubNum = SubFolderList{i,3};
    HOME = strcat('D:\Users\zhaga\Documents\MATLAB\AFOSR_Data\Subjects\Sub_0', num2str(SubNum),'\ToUpload\');
   if(i == 65 | i == 11 | i==13 | i==21 | i==50 | i ==53 | i == 71 | i == 52 | i == 28 | i == 41 | i == 46 | i == 51 | i == 78)
       continue
   end
   for j = 1:2
        cd(HOME);
        load(strcat('MentalStates_S0',num2str(SubNum),'_',int2str(j),'.mat'));
        [CL_H_win]  =  logicalMask2TimeWindows(CogLoadHigh, Timeline);
        [CL_L_win]  =  logicalMask2TimeWindows(CogLoadLow, Timeline);
        [Dis_H_win] =  logicalMask2TimeWindows(DistractionHigh, Timeline);
        [Dis_L_win] =  logicalMask2TimeWindows(DistractionLow, Timeline);
        [Urg_H_win] =  logicalMask2TimeWindows(UrgencyHigh, Timeline);
        [Urg_L_win] =  logicalMask2TimeWindows(UrgencyLow, Timeline);
        [MW_H_win]  =  logicalMask2TimeWindows(MindWanderHigh, Timeline);
        [MW_L_win]  =  logicalMask2TimeWindows(MindWanderLow, Timeline);
        [Int_H_win] =  logicalMask2TimeWindows(InterferenceHigh, Timeline);
        [Int_L_win] =  logicalMask2TimeWindows(InterferenceLow, Timeline);
        
        SubTrialMask = (B(:,1) == i) & (B(:,2) == j);
       
        for k = 1:length(VarNames)
            sz = length( eval(VarNames{k}));
            if(sz>2)
                maskFilt = 2:2:((sz-1)*2);
                bb(1 : sz*2) = eval(VarNames{k})'; 
                [N,edges,bin] = histcounts(B(SubTrialMask,3),bb);
                N(maskFilt) = [];
                Bb = B(SubTrialMask,4);
                IndBlks.Num( i,j,k) = sum(N);
                IndBlks.Freq(i,j,k) = sum(N) / sum(diff(eval(VarNames{k})'));
                IndBlks.Dur( i,j,k) = mean(Bb(~(bin==0) | sum(bin == maskFilt,2)));
            elseif(sz<=2)
                bb = eval(VarNames{k})'; 
                [N,edges,bin] = histcounts(B(SubTrialMask,3),bb);
                Bb = B(SubTrialMask,4);
                IndBlks.Num( i,j,k) = sum(N);
                IndBlks.Freq(i,j,k) = sum(N) / sum(diff(eval(VarNames{k})'));
                IndBlks.Dur( i,j,k) = mean(Bb(~(bin==0)));
            end  
            clear sz N edges bin maskFilt bb
        end
        
   end
end